<template>
  <div class="settings-page">
    <div class="container page">
      <div class="row">

        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">Your Settings</h1>

          <form @submit.prevent="onSubmit">
            <fieldset>
                <fieldset class="form-group">
                  <input v-model="user.image" class="form-control" type="text" placeholder="URL of profile picture">
                </fieldset>
                <fieldset class="form-group">
                  <input v-model="user.username" class="form-control form-control-lg" type="text" placeholder="Your Name">
                </fieldset>
                <fieldset class="form-group">
                  <textarea v-model="user.bio" class="form-control form-control-lg" rows="8" placeholder="Short bio about you"></textarea>
                </fieldset>
                <fieldset class="form-group">
                  <input v-model="user.email" class="form-control form-control-lg" type="text" placeholder="Email">
                </fieldset>
                <fieldset class="form-group">
                  <input class="form-control form-control-lg" type="password" placeholder="New Password">
                </fieldset>
                <button class="btn btn-lg btn-primary pull-xs-right" type="submit">
                  Update Settings
                </button>
            </fieldset>
          </form>

          <hr>

          <button class="btn btn-outline-danger" @click="logout">
            Or click here to logout.
          </button>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { updateUser } from '@/api'
const Cookie = process.client ? require('js-cookie') : undefined

export default {
  name: 'SettingsPage',
  middleware: 'auth',
  data () {
    return {
      user: {}
    }
  },
  computed: {
    ...mapState({
      userData: state => state.user,
    })
  },
  head () {
    return {
      title: 'Settings - RealWorld'
    }
  },
  created () {
    this.user = Object.assign({}, this.userData)
    this.lock = false
  },
  methods: {
    ...mapMutations(['setUser']),
    async onSubmit () {
      if (this.lock) return
      this.lock = true

      const { data } = await updateUser({ user: this.user })
      this.lock = false

      // 更新用户信息
      this.setUser(data.user)

      // 更新 cookie
      Cookie.set('user', data.user)
    },
    logout () {
      this.setUser(null)
      Cookie.remove('user')

      this.$router.push({
        name: 'home'
      })
    }
  }
}
</script>
